﻿using System.Diagnostics;

namespace HCore
{
    public class PrecisionTimer
    {
        public Fix TimerScale() => _timeScale;

        public Fix deltaTime => _frameTime;

        public Fix frameRate => _frameRate;

        public Fix totalTime => _totalTime;

        public Fix currentTime => _frameCount * _frameTime;
        public int frameCount => _frameCount;

        private Stopwatch _stopwatch;
        private int _frameCount;
        private Fix _lastTime = 0;
        private Fix _totalTime;
        private Fix _frameTime;
        private Fix _frameRate;
        private Fix _timeScale = 1;

        public PrecisionTimer(Fix fps)
        {
            _stopwatch = new Stopwatch();
            _frameRate = fps;
            _timeScale = 1;
        }

        public void Start()
        {
            _stopwatch.Start();
            _frameTime = Fix.One / _frameRate;
            _lastTime = (Fix) (int) _stopwatch.ElapsedMilliseconds / 1000;
            _totalTime = Fix.Zero;
            _frameCount = 0;
        }

        public bool ReadyForNextFrame()
        {
            Fix current = (Fix) (int) _stopwatch.ElapsedMilliseconds / 1000;
            Fix delta = (current - _lastTime) * _timeScale;

            _totalTime += delta;
            _lastTime = current;
            if (_totalTime >= _frameCount * _frameTime)
            {
                return true;
            }

            return false;
        }

        public void IntoNextFrame()
        {
            _frameCount++;
        }

        public void SetTimerScale(Fix scale)
        {
            _timeScale = scale;
        }
    }
}